import {useTHNavigation} from "../../utils/navigation"
import {loginUserAPI, sendCodeAPI} from "../../api"
import React, {useState, useEffect, useRef} from "react"
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ImageBackground,
  StatusBar,
  Dimensions,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from "react-native"
import {setIsNew, setToken} from "../../store/user/userSlice"
import {useDispatch} from "react-redux"
import {useLoading, useShowToast} from "../../hooks"

const Login = () => {
  const [phoneNumber, setPhoneNumber] = useState("")
  const [verificationCode, setVerificationCode] = useState("")
  const [showVerification, setShowVerification] = useState(false)
  const [countdown, setCountdown] = useState(60)
  const [isTimerRunning, setIsTimerRunning] = useState(false)
  const codeInputRef = useRef<TextInput>(null)
  const navigation = useTHNavigation()
  const dispatch = useDispatch()
  const showToast = useShowToast()
  const loading = useLoading()

  // 处理倒计时
  useEffect(() => {
    let timer: NodeJS.Timeout | undefined
    if (isTimerRunning && countdown > 0) {
      timer = setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)
    } else if (countdown === 0) {
      setIsTimerRunning(false)
      setCountdown(60)
    }

    return () => {
      if (timer) {
        clearTimeout(timer)
      }
    }
  }, [countdown, isTimerRunning])

  // 自动聚焦到验证码输入框
  useEffect(() => {
    if (showVerification && codeInputRef.current) {
      setTimeout(() => {
        codeInputRef.current?.focus()
      }, 300)
    }
  }, [showVerification])

  const handleSendVerificationCode = async () => {
    if (!phoneNumber || !/^1[3-9]\d{9}/.test(phoneNumber)) {
      showToast("手机号格式不正确")
      return
    }
    // 模拟发送验证码
    const close = loading()
    await sendCodeAPI({phone: phoneNumber}) // 发送验证码
    showToast("验证码发送成功")
    close()

    setShowVerification(true)
    setIsTimerRunning(true)
  }

  const handleVerify = async (code: string) => {
    if (/^\d{6}$/.test(code)) {
      const close = loading()
      const res = await loginUserAPI({
        phone: phoneNumber,
        vcode: code,
      })
      close()
      showToast("登录成功")
      dispatch(setIsNew(res.isNew))
      dispatch(setToken(res.token))
      navigation.push(res.isNew ? "UserInfo" : "Tabbar")
    } else {
      showToast("验证码格式不正确")
    }
  }

  // 重新发送验证码按钮点击事件
  const handleResendCode = () => {
    if (!isTimerRunning) {
      // 模拟重新发送验证码
      showToast("验证码已重新发送")
      setCountdown(60)
      setIsTimerRunning(true)
    }
  }

  return (
    <View style={styles.container}>
      <StatusBar translucent backgroundColor="transparent" />
      <View style={styles.backgroundContainer}>
        <ImageBackground
          source={require("../../res/profileBackground.jpg")}
          style={styles.backgroundImage}
        />
      </View>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.contentContainer}>
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}>
          {!showVerification ? (
            // 手机号登录页面
            <View style={styles.loginContainer}>
              <Text style={styles.title}>手机号登录注册</Text>
              <View style={styles.inputContainer}>
                <TextInput
                  style={styles.input}
                  placeholder="请输入手机号码"
                  placeholderTextColor="#999"
                  keyboardType="phone-pad"
                  maxLength={11}
                  value={phoneNumber}
                  onChangeText={setPhoneNumber}
                />
              </View>
              <TouchableOpacity
                style={styles.button}
                onPress={handleSendVerificationCode}>
                <Text style={styles.buttonText}>获取验证码</Text>
              </TouchableOpacity>
            </View>
          ) : (
            // 验证码输入页面
            <View style={styles.loginContainer}>
              <Text style={styles.title}>输入6位验证码</Text>
              <Text style={styles.subtitle}>已发送到+86 {phoneNumber}</Text>

              <View style={styles.codeInputContainer}>
                {/* 实际输入框 */}
                <TextInput
                  ref={codeInputRef}
                  style={styles.hiddenCodeInput}
                  keyboardType="number-pad"
                  maxLength={6}
                  value={verificationCode}
                  onChangeText={text => {
                    setVerificationCode(text)
                    if (text.length === 6) {
                      handleVerify(text)
                    }
                  }}
                  caretHidden={false}
                />

                {/* 验证码显示区域 */}
                <View style={styles.codeDisplayContainer}>
                  {[0, 1, 2, 3, 4, 5].map(index => (
                    <View key={index} style={styles.codeBox}>
                      {index < verificationCode.length ? (
                        <Text style={styles.codeText}>
                          {verificationCode[index]}
                        </Text>
                      ) : index === verificationCode.length ? (
                        <View style={styles.cursor} />
                      ) : null}
                    </View>
                  ))}
                </View>
              </View>

              <TouchableOpacity
                style={[styles.button, isTimerRunning && styles.disabledButton]}
                onPress={handleResendCode}
                disabled={isTimerRunning}>
                <Text style={styles.buttonText}>
                  {isTimerRunning ? `重新获取(${countdown}s)` : "重新获取"}
                </Text>
              </TouchableOpacity>
            </View>
          )}
        </ScrollView>
      </KeyboardAvoidingView>
    </View>
  )
}

const {height} = Dimensions.get("window")

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundContainer: {
    height: height / 3, // 屏幕高度的三分之一
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    zIndex: 1,
  },
  backgroundImage: {
    width: "100%",
    height: "100%",
    resizeMode: "cover",
  },
  contentContainer: {
    flex: 1,
    zIndex: 2,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: "center",
    paddingTop: height / 3 + 20, // 给背景图留出空间，加一点额外间距
    paddingBottom: 20,
  },
  loginContainer: {
    marginHorizontal: 20,
    alignItems: "center",
  },
  title: {
    fontSize: 28,
    fontWeight: "bold",
    color: "#333",
    marginBottom: 20,
  },
  subtitle: {
    fontSize: 16,
    color: "#666",
    marginBottom: 30,
  },
  inputContainer: {
    width: "100%",
    borderBottomWidth: 1,
    borderBottomColor: "#ccc",
    marginBottom: 40,
  },
  input: {
    fontSize: 18,
    paddingVertical: 10,
    color: "#333",
  },
  button: {
    width: "100%",
    height: 50,
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(186, 111, 220, 0.8)",
    marginBottom: 15,
  },
  disabledButton: {
    backgroundColor: "rgba(186, 111, 220, 0.5)",
  },
  buttonText: {
    color: "white",
    fontSize: 18,
    fontWeight: "bold",
  },
  codeInputContainer: {
    width: "100%",
    marginBottom: 40,
    position: "relative",
  },
  hiddenCodeInput: {
    position: "absolute",
    width: "100%",
    height: 60,
    opacity: 0,
    zIndex: 1,
  },
  codeDisplayContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%",
    marginTop: 10,
  },
  codeBox: {
    width: "15%",
    height: 50,
    borderBottomWidth: 2,
    borderBottomColor: "#ccc",
    justifyContent: "center",
    alignItems: "center",
  },
  codeText: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#333",
  },
  cursor: {
    width: 2,
    height: 30,
    backgroundColor: "#9370DB",
    marginBottom: 2,
    opacity: 1,
  },
})

export default Login
